package com.windward.vii.service;

import com.windward.vii.common.Constants;
import com.windward.vii.dao.entity.*;
import com.windward.vii.dao.mapper.*;
import com.windward.vii.service.rongcloud.RongCloudProxy;
import com.windward.vii.utils.ThreadPoolManager;
import com.windward.vii.service.rongcloud.messages.TxtMessage;
import com.windward.vii.service.rongcloud.models.CodeSuccessResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

@Component
public class AssetUserAccountService {

    private static Logger logger = LoggerFactory.getLogger(AssetUserAccountService.class);

    @Resource
    UserMapper userMapper;
    @Resource
    DeviceMapper deviceMapper;
    @Resource
    AssetUserAccountMapper assetUserAccountMapper;
    @Resource
    RongCloudProxy rongCloudProxy;
    @Resource
    AssetPromotionMapper assetPromotionMapper;
    @Resource
    AssetUserRechargeMapper assetUserRechargeMapper;

    public AssetUserAccount selectByUid(Long uid) {
        return assetUserAccountMapper.selectByUid(uid);
    }

    public boolean updateUserById(AssetUserAccount userAccount) {
        AssetUserAccount dbUser = assetUserAccountMapper.selectByUid(userAccount.getUid());
        int row = assetUserAccountMapper.updateByUidSelective(userAccount);
        if(row > 0) {
            if(dbUser != null) {
                // 如果修改头像，设置头像审核状态为：待审核
                if(dbUser.getAvatar() == null || !dbUser.getAvatar().equals(userAccount.getAvatar())) {
                    userAccount.setAvatarStatus(Constants.User.AVATAR_STATUS_INIT);
                }
                // 如果修改昵称，更新融云nickname
                if(dbUser.getNickname() == null || !dbUser.getNickname().equals(userAccount.getNickname())) {
                    asyncUpdateImNickname(userAccount);
                }
                // 用户注册完成，发送IM提示
                if(dbUser.getInfoStatus() == Constants.User.INFO_STATUS_INIT) {
                    asyncSendRegisterImTips(userAccount.getUid());
                }
                // 用户注册：首次完善资料时，而且单个设备只能注册一次，给用户充值
//                if(!dbUser.getIsReceiveRegisterCoin()
//                        && dbUser.getInfoStatus() == Constants.User.INFO_STATUS_INIT
//                        && userAccount.getSex() == Constants.User.SEX_MEN) {
//                    User user = userMapper.selectByPrimaryKey(dbUser.getUid());
//                    if(user != null && user.getLastLoginDeviceId() != null) {
//                        Device device = deviceMapper.selectByPrimaryKey(user.getLastLoginDeviceId());
//                        if(device != null && !device.getIsReceiveRegisterCoin()) {
//                            AssetPromotion assetPromotion = assetPromotionMapper.selectByTime(dbUser.getCreateTime());
//                            if(assetPromotion != null && assetPromotion.getCoinUsed() < assetPromotion.getCoinTotal()) {
//                                // 生成充值成功记录
//                                AssetUserRecharge assetUserRecharge = new AssetUserRecharge();
//                                assetUserRecharge.setUid(dbUser.getUid());
//                                assetUserRecharge.setOrderId(0L);
//                                assetUserRecharge.setPayType(Constants.Order.PAY_TYPE_PROMOTION_REGISTER);
//                                assetUserRecharge.setAmount(0);
//                                assetUserRecharge.setCoin(assetPromotion.getCoinUnit());
//                                assetUserRecharge.setTerminalType(device.getTerminalType());
//                                assetUserRecharge.setCreateTime(new Date());
//                                if(assetUserRechargeMapper.insertSelective(assetUserRecharge) < 1) {
//                                    logger.error("生成充值成功记录失败");
//                                }
//
//                                // 对新注册用户，增加赠送V钻
//                                AssetUserAccount updateUserAccount = new AssetUserAccount();
//                                updateUserAccount.setId(dbUser.getId());
//                                updateUserAccount.setIsReceiveRegisterCoin(true);
//                                updateUserAccount.setAvailableReceiveCoin(assetPromotion.getCoinUnit());
//                                updateUserAccount.setUpdateTime(new Date());
//                                assetUserAccountMapper.updateByPrimaryKeySelective(updateUserAccount);
//
//                                // 设置设备Device已获取注册V钻
//                                Device updateDevice = new Device();
//                                updateDevice.setId(device.getId());
//                                updateDevice.setIsReceiveRegisterCoin(true);
//                                deviceMapper.updateByPrimaryKeySelective(updateDevice);
//
//                                AssetPromotion updateAssetPromotion = new AssetPromotion();
//                                updateAssetPromotion.setId(assetPromotion.getId());
//                                updateAssetPromotion.setCoinUsed(assetPromotion.getCoinUsed() + assetPromotion.getCoinUnit());
//                                assetPromotionMapper.updateByPrimaryKeySelective(updateAssetPromotion);
//                            }
//                        }
//                    }
//                }
            }
        }
        return row > 0;
    }

    private void asyncUpdateImNickname(AssetUserAccount userAccount) {
        ThreadPoolManager.getInstance().addExecuteTask(new Runnable() {
            @Override
            public void run() {
                try {
                    logger.info("asyncUpdateImNickname: im.user.refresh, uid={}, nickname={}, avatar={}", userAccount.getUid(), userAccount.getNickname(), userAccount.getAvatar());
                    CodeSuccessResult messagePublishSystemResult = rongCloudProxy.getInstance().user.refresh(
                            String.valueOf(userAccount.getUid()),
                            userAccount.getNickname(),
                            userAccount.getAvatar());
                    logger.info("asyncUpdateImNickname: im.user.refresh.result={}", messagePublishSystemResult.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public void asyncSendRegisterImTips(Long uid) {
        ThreadPoolManager.getInstance().addExecuteTask(new Runnable() {
            @Override
            public void run() {
                try {
                    String fromUserId = "3";
                    String[] toUserId = {String.valueOf(uid)};
                    String content = "嗨！欢迎来到Vii，与高颜值美女网红一对一视频聊天社区~\n"
                            + "Vii是一个时尚、阳光、绿色的视频聊天社区，希望你能和Vii一起维护绿色的聊天环境，我们拒绝不雅的言行举止，被举报经核实后，永久封号哦~\n"
                            + "赶快去和高颜值、正能量的Vii Girl视频聊天吧~";
                    TxtMessage txtMessage = new TxtMessage(content, "");
                    String pushContent = "嗨！欢迎来到Vii，与高颜值美女网红一对一视频聊天社区~";
                    logger.info("asyncSendRegisterTips: fromUserId={}, toUserId={}", fromUserId, toUserId);
                    CodeSuccessResult messagePublishSystemResult = rongCloudProxy.getInstance().message.publishPrivate(
                            fromUserId,
                            toUserId,
                            txtMessage,
                            pushContent,"","1", 1, 0, 1, 0
                            );
                    logger.info("asyncSendRegisterTips: result={}", messagePublishSystemResult.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public boolean updateOnlineStatusByUid(Long uid, Integer onlineStatus) {
        try {
            assetUserAccountMapper.updateOnlineStatusByUid(uid, onlineStatus);
            return true;
        } catch (Exception e) {
            return false;
        }
    }



}
